﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace EMIS
{
    class Http
    {
        const string UserAgent = "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.1; .NET CLR 4.0)";
        HttpClient Web = new HttpClient();
        StringBuilder PostString = new StringBuilder();
        public Encoding Encoding = Encoding.UTF8;
        public Http()
        {
            Web.Proxy = null;
        }

        public void Add(string name, string value)
        {
            name = System.Web.HttpUtility.UrlEncode(name, Encoding);
            value = System.Web.HttpUtility.UrlEncode(value, Encoding);
            if (PostString.Length != 0) PostString.Append('&');
            PostString.Append(name);
            PostString.Append('=');
            PostString.Append(value);
        }
        public void Clear() { PostString.Clear(); }

        public string Get(string url)
        {
            try
            {
                Web.Headers.Add(HttpRequestHeader.UserAgent, UserAgent);
                Web.Encoding = Encoding;
                return Web.DownloadString(url);
            }
            catch { return null; }
        }

        public string Post(string url)
        {
            try
            {
                Web.Headers.Add(HttpRequestHeader.UserAgent, UserAgent);
                Web.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
                Web.Encoding = Encoding;
                return Web.UploadString(url, PostString.ToString());
            }
            catch { return null; }
            finally { Clear(); }
        }

        public byte[] Download(string url)
        {
            try
            {
                Web.Headers.Add(HttpRequestHeader.UserAgent, UserAgent);
                return Web.DownloadData(url);
            }
            catch { return null; }
        }

        class HttpClient : WebClient
        {
            public bool AllowAutoRedirect = false;
            public CookieContainer Cookies = new CookieContainer();
            protected override WebRequest GetWebRequest(Uri address)
            {
                WebRequest request = base.GetWebRequest(address);
                if (request is HttpWebRequest)
                {
                    HttpWebRequest httpRequest = request as HttpWebRequest;
                    httpRequest.AllowAutoRedirect = AllowAutoRedirect;
                    httpRequest.CookieContainer = Cookies;
                }
                return request;
            }
            public WebRequest GetWebRequest(string url)
            {
                return GetWebRequest(new Uri(url));
            }
        }
    }
}
